package edu.friday.common.security.service;


import edu.friday.common.constant.Constants;
import edu.friday.common.security.LoginUser;
import edu.friday.utils.IdUtils;
import edu.friday.utils.MyRedisCache;
import edu.friday.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class MyTokenService {
    @Value("${token.header}")
    private String header;

    @Value("${token.secret}")
    private String secret;

    @Value("${token.expireTime}")
    private int expireTime;



    protected static final long MILLIS_SECONDS=1000;
    protected static final long ONE_MINUTE = 60 * MILLIS_SECONDS;
    protected static final long MILLS_MINUTE_TEN = 20 * ONE_MINUTE;


    @Autowired
    private MyRedisCache redisCache;



    public String createToken(LoginUser loginUser) {
        String token= IdUtils.fastUUID();
        loginUser.setToken(token);
        refreshToken(loginUser);
        Map<String,Object> claim=new HashMap<String,Object>();
        claim.put(Constants.LOGIN_USER_KEY,token);
        return createToken(claim);
    }

    private void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * ONE_MINUTE);
        String userKey = getTokenKey(loginUser.getToken());

        redisCache.setCacheObject(userKey,loginUser,expireTime, TimeUnit.MINUTES);
    }

    private String createToken(Map<String,Object> claim) {
        String token= Jwts.builder().setClaims(claim)
                .signWith(SignatureAlgorithm.HS512,secret).compact();
        return token;
    }

    private String getTokenKey(String token) {
        return Constants.LOGIN_USER_KEY + token;
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    public LoginUser getLoginUser(HttpServletRequest request) {
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims=parseToken(token);
            String uuid=(String)claims.get(Constants.LOGIN_USER_KEY);
            String userKey=getTokenKey(uuid);
            LoginUser user=redisCache.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    public void verifyToken(LoginUser loginUser) {
        long now = System.currentTimeMillis();
        long expire=loginUser.getExpireTime();
        if (expire-now<=MILLS_MINUTE_TEN){
            refreshToken(loginUser);
        }
    }
}
